/**
 * 保存和恢复表格设置
 */
import {mapGetters, mapActions } from 'vuex'
import {setItem, getItem, removeItem} from '../../assets/js/storage.js'
import {deepCopyObjArray, count} from '../../assets/js/help.js'
import '../../assets/js/extensionFn.js'
export default {
  created () {
  },
  computed: {
    ...mapGetters({
      isSync: 'getIsSyncUserSetting'
    })
  },
  watch: {
    isSync: function(val) {
      if(val) {
        this.recoverSetting();
      }
    },
  },
  methods: {
    ...mapActions({
      setUserSetting: 'setUserSetting' 
    }),
    //保存表格设置
    saveSetting () {
      let self = this;

      let name = this.thisRouter;
      let _storage = getItem(name);
      let list = [];
      let show = [], hide = [];
      _storage = _storage ? _storage : {};

      list = this.saveListByIsMulti(this.theadsArr);

      _storage.list = list;
      setItem(name,_storage);
      let params = {
            userToken: this.userToken,
            tableName: name,
            tableData: JSON.stringify(_storage)
          };
      this.setUserSetting(params).then(res => {},err => {
        self.showToast('表格数据上传失败！', 2);
      });
    },
    // 根据保存的设置恢复表格
    recoverSetting () {
      let _this = this;
      let name = this.thisRouter;
      let _storage = getItem(name);
      _storage = _storage ? _storage : {};
      if(_storage && _storage.list) {
        let arr = this.theadsArr,
            sortBy = _storage.list,
            sortByObj = this.recoverListByIsMulti(sortBy),
            sortList = sortByObj.list,
            sortSecList = sortByObj.secList,
            resList = [],
            widthObj = _storage.wid,
            minWidthObj = _storage.minW;

        sortList = sortList.map((x, i) => {
          let _x = '' + x
          if ((_x).indexOf('!') > -1) {
            _x = _x.substr(1)
            arr[i].checked = false
          }
          return Number(_x)
        })

        resList = arr.sort(this.sortByListIndex(sortList))
        // this.theadsArr = resList

        if(widthObj) {
          this.recoverWidth(widthObj, 'width');
        }
        if(minWidthObj) {
          this.recoverWidth(minWidthObj, 'minWidth');
        }

        // let tableDatas = deepCopyObjArray(this.theadsInfo),
        //     sec_show = [], sec_hide = [], //二级表头的顺序数据数组
        //     showRes = _storage.show, hideRes = _storage.hide, //localStorage保存的原始的数据
        //     show = [], hide = [];
        // let _datas = [],_showArr = [],_hideArr = [];
        // let widthObj = _storage.wid,
        //     minWidthObj = _storage.minW;
            
        // let showObj = this.recoverListByIsMulti(showRes);
        // show = showObj.list;
        // sec_show = showObj.secList;

        // let hideObj = this.recoverListByIsMulti(hideRes);
        // hide = hideObj.list;
        // sec_hide = hideObj.secList;
        
        // _datas = this.apartByDisplay(tableDatas,show,hide);
        // _showArr = deepCopyObjArray(_datas.show);
        // _hideArr = deepCopyObjArray(_datas.hide);

        // _showArr.sort(this.sortByIndex(show));
        // _hideArr.sort(this.sortByIndex(hide));

        // _showArr = deepCopyObjArray(this.recoverSecondHeader(sec_show, _showArr));
        // _hideArr = deepCopyObjArray(this.recoverSecondHeader(sec_hide, _hideArr));

        // this.theadShowed = _showArr.slice(0);
        // this.theadHidden = _hideArr.slice(0);

        // if(widthObj) {
        //   this.recoverWidth(widthObj, 'width');
        // }
        // if(minWidthObj) {
        //   this.recoverWidth(minWidthObj, 'minWidth');
        // }
      }
      delete _storage.show
      delete _storage.hide
      setItem(name,_storage)
    },
    //根据是否有二级表头恢复列的顺序，返回一级表头的顺序数组，和二级表头的数据
    recoverListByIsMulti (arr) {
      let list = [],
          secList = [];
      for(let i = 0, len = arr.length; i < len; i++) {
        let _data = arr[i]
        if(Number.isInteger(_data) || typeof _data === 'string') {
          list.push(_data);
        } else {
          // let _obj = arr[i];
          secList.push(_data);
          for(let n in _data) {
            list.push(Number(n));
          }
        }
      }
      return {
        list: list,
        secList: secList
      }
    },
    sortByListIndex (arr) {
      return function(a, b) {
        let Val1 = arr.indexOf(a.index);
        let Val2 = arr.indexOf(b.index);
        return Val1 - Val2;
      }
    },
    //根据是否有多级表头保存列表数据
    saveListByIsMulti (arr, isHide) {
      let result = [];
      for(let i = 0, len = arr.length; i< len; i++) {
        let _item = arr[i],
            _index = _item.index,
            _idx = i,
            checked = _item.checked,
            _res = {};
        if(_item.isMultiHeader) { //如果是二级表头的情况下，保存的结构为 {1:{0:[1,2]}} 第一层的1 表示当前表头的一级头的index, 第二层的0表示 当前第一层表头在保存的数组中的索引值， [1, 2]表示二级表头 的index值
        //这样子做的目的是 设置二级表头的显示隐藏时，如果是显示或隐藏部分二级表头的时候， 需要利用 该一级表头的在数组的位置来获取其子表头 children
          let _arr = _item.children,
              _resArr = [],
              _obj = {},
              _subObj = {};

          for(let j = 0, len = _arr.length; j < len; j++) {
            let _arrj = _arr[j]
            let _arr_idx = _arrj.index
            let _checked = _arrj.checked
            let _re = checked ? (_checked ? _arr_idx : '!' + _arr_idx) : '!' + _arr_idx
            _resArr.push(_re);
          }
          
          _subObj[_idx] = _resArr;
          _obj[_index] = _subObj;
          result.push(_obj);
        } else {
          _res = checked ? _index : '!' + _index
          result.push(_res);
        }
      }
      return result;
    },
    //恢复二级表头的顺序
    recoverSecondHeader (arr, targetArr) {
      let _this = this;
      for(let i = 0, len = arr.length; i < len; i++) {
        let _obj = arr[i],
            _idx = -1,
            index = -1,
            children = [],
            _subObj = {},
            _list = [];
        for(let n in _obj) {
          _idx = Number(n);
          _subObj = _obj[n];
          for(let x in _subObj) {
            index = Number(x);
            _list = _subObj[x];
          }
        }
        children = targetArr[index].children;
        list = list.map((x, i) => {
          let _x = '' + x
          if ((_x).indexOf('!') > -1) {
            _x = _x.substr(1)
            children[i].checked = false
          }
          return Number(_x)
        })
        children.sort(_this.sortByListIndex(_list))
      }
      return targetArr;
    },
    //根据是否有二级表头恢复列的顺序，返回一级表头的顺序数组，和二级表头的数据
    recoverListByIsMulti1 (arr) {
      let list = [],
          secList = [];
      for(let i = 0, len = arr.length; i < len; i++) {
        if(Number.isInteger(arr[i])) {
          list.push(arr[i]);
        } else {
          let _obj = arr[i];
          secList.push(_obj);
          for(let n in _obj) {
            list.push(Number(n));
          }
        }
      }
      return {
        list: list,
        secList: secList
      }
    },
    //恢复列宽
    recoverWidth (obj, widthName) {
      let showArr = this.theadsArr;
      for(let k in obj) {
        let value = obj[k],
            keyArr = k.split('-'),
            _k = k,
            _sec_i = -1,
            _idx = -1,
            _sec_idx = -1,
            Item = {};
        if(keyArr.length > 1) {
          _k = keyArr[0];
          _sec_i = keyArr[keyArr.length - 1];
        }
        _idx = showArr.findByKey('index', _k);//找到数据列表中，index = k的对象的索引
        if(_idx > -1) {
          if(_sec_i > -1) {
            _sec_idx = showArr[_idx].children.findByKey('index', _sec_i);
            if(_sec_i > -1) {
              Item = showArr[_idx].children[_sec_idx];
            }
          } else {
            Item = showArr[_idx];
          }
          if(Item) {
            Item[widthName] = Number(value);
          }
          
        }
      }
    },
    //根据保存的列的显示状态把数据分成两个数组（一个是显示状态的数组，一个是隐藏状态的数组）
    apartByDisplay (dataArr, show, hide) {
      let _showArr = [],_hideArr = [];
      for(let i = 0, len = dataArr.length; i < len; i++) {
        let thisData = dataArr[i];
        let index = thisData.index;
        if(show.indexOf(index) > -1) {
          _showArr.push(thisData);
          // continue;
        }
        if(hide.indexOf(index) > -1) {
          _hideArr.push(thisData);
          // continue;
        }
      }
      return {
        show: _showArr,
        hide: _hideArr
      }
    },
    //根据表格头的index在保存的数组的位置排序
    sortByIndex (arr) {
      return function(a, b) {
        let Val1 = arr.indexOf(a.index);
        let Val2 = arr.indexOf(b.index);
        return Val1 - Val2;
      }
    }
  }
}